<template>
  <div class="dashboard-container">
    <!-- 添加加载状态和错误提示 -->
    <div v-loading="loading" :element-loading-text="'加载中...'" class="chart-wrapper">
      <el-alert
        v-if="error"
        :title="error"
        type="error"
        show-icon
        :closable="false"
        style="margin-bottom: 15px;"
      />
      <!-- 当没有错误且数据为空时显示提示 -->
      <el-empty v-if="!error && (!statistics.subjects || statistics.subjects.length === 0)" description="暂无学习数据" />
      
      <!-- 有数据时显示图表 -->
      <div v-if="!error && statistics.subjects && statistics.subjects.length > 0" class="charts-container">
        <!-- 饼图部分 -->
        <div class="chart-card">
          <div class="header-section">
            <div class="title-group">
              <h1>学习时间分布</h1>
              <div class="date-countdown-info">
                <span class="date-info">{{ currentDate }}</span>
                <span class="countdown-info">
        距离考试还有 <strong>{{ countdownInfo.days }}</strong> 天 
        <strong>{{ countdownInfo.hours }}</strong> 时 
        <strong>{{ countdownInfo.minutes }}</strong> 分 
        <strong>{{ countdownInfo.seconds }}</strong> 秒
        </span>
                
              </div>
            </div>
            <el-radio-group v-model="timeRange" size="default">
              <el-radio-button value="day" label="当天">当天</el-radio-button>
              <el-radio-button value="week" label="本周">本周</el-radio-button>
              <el-radio-button value="month" label="本月">本月</el-radio-button>
              <el-radio-button value="year" label="全部">全部</el-radio-button>
            </el-radio-group>
          </div>

          <div class="chart-section">
            <div class="chart-area">
              <div class="center-stats">
                <div class="time-display">
                  <div class="time-block">
                    <div class="time-value">{{ formatTimeValue(statistics.hours) }}</div>
                    <div class="time-label">时</div>
                  </div>
                  <div class="time-separator">:</div>
                  <div class="time-block">
                    <div class="time-value">{{ formatTimeValue(statistics.minutes) }}</div>
                    <div class="time-label">分</div>
                  </div>
                  <div class="time-separator">:</div>
                  <div class="time-block">
                    <div class="time-value">{{ formatTimeValue(statistics.seconds) }}</div>
                    <div class="time-label">秒</div>
                  </div>
                </div>
                <div class="total-label">总学习时长</div>
              </div>
              <div ref="pieChart" class="pie-chart"></div>
            </div>

            <div class="stats-grid">
              <div v-for="subject in statistics.subjects" 
                  :key="subject.label" 
                  class="stat-item"
                  :class="{ active: subject.seconds > 0 }">
                <div class="stat-info">
                  <div class="stat-color" :style="{ backgroundColor: subject.color }"></div>
                  <span class="stat-name">{{ subject.label }}</span>
                </div>
                <div class="stat-time">
                  <span class="stat-hours">{{ formatTimeValue(subject.hours) }}</span>
                  <span class="stat-separator">:</span>
                  <span class="stat-minutes">{{ formatTimeValue(subject.minutes) }}</span>
                  <span class="stat-separator">:</span>
                  <span class="stat-seconds">{{ formatTimeValue(subject.seconds) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 学习时间趋势折线图 -->
        <div class="chart-card">
          <div class="header-section">
            <div class="title-group">
              <h1>学习时间趋势</h1>
            </div>
          </div>
          <div class="trend-chart-container">
            <div ref="lineChart" class="trend-chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import request from '@/utils/request'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

// 根据字符串生成唯一的颜色
const generateColorFromString = (str) => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  
  // 避免与已有颜色太相似
  const hue = ((hash % 360) + 360) % 360;
  const saturation = 70 + (hash % 20); // 70-90%
  const lightness = 45 + (hash % 10);  // 45-55%
  
  return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}

// 当前日期
const currentDate = computed(() => {
  return dayjs().format('YYYY年MM月DD日')
})

// 考试日期和倒计时
const examDate = ref('2025-12-20') // 设置考试日期

const countdownInfo = ref({
  days: 0,
  hours: 0,
  minutes: 0,
  seconds: 0
})
// 定义定时器变量
let countdownTimer = null

// 更新倒计时的函数
const updateCountdown = () => {
  const now = dayjs()
  const targetDate = dayjs(examDate.value)
  const diffSeconds = targetDate.diff(now, 'second')

  if (diffSeconds <= 0) {
    // 倒计时结束，清除定时器并将倒计时信息设为 0
    countdownInfo.value = {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0
    }
    clearInterval(countdownTimer)
    return
  }

  // 计算天、小时、分钟和秒
  const days = Math.floor(diffSeconds / (3600 * 24))
  const remainingSecondsAfterDays = diffSeconds % (3600 * 24)
  const hours = Math.floor(remainingSecondsAfterDays / 3600)
  const remainingSecondsAfterHours = remainingSecondsAfterDays % 3600
  const minutes = Math.floor(remainingSecondsAfterHours / 60)
  const seconds = remainingSecondsAfterHours % 60

  // 更新倒计时信息
  countdownInfo.value = {
    days,
    hours,
    minutes,
    seconds
  }
}

onMounted(() => {
  // 组件挂载时启动倒计时更新，每秒执行一次
  countdownTimer = setInterval(updateCountdown, 1000)
  // 立即执行一次更新以初始化倒计时
  updateCountdown()
})


// 时间范围选择
const timeRange = ref('week')
const pieChart = ref(null)
const lineChart = ref(null)

// 学科数据
const subjectList = ref([])

// 获取学科列表数据
const fetchSubjectList = async () => {
  loading.value = true
  error.value = null
  
  try {
    // 根据 timeRange 映射 timeStatus
    let timeStatus;
    switch (timeRange.value) {
      case 'day':
        timeStatus = 1;
        break;
      case 'week':
        timeStatus = 2;
        break;
      case 'month':
        timeStatus = 3;
        break;
      default:
        timeStatus = 0;
    }
    
    const response = await request.get('/api/studyMission/list', {
      params: {
        timeStatus
      }
    })
    if (response.code === '200') {
      console.log('API返回数据:', response.data)
      subjectList.value = response.data || []
      console.log('处理后的学习记录:', subjectList.value)
    } else {
      error.value = response.message || '获取学习任务记录失败'
      ElMessage.error(error.value)
    }
  } catch (error) {
    console.error('获取学习任务记录失败:', error)
    error.value = '网络错误，请稍后重试'
    ElMessage.error('获取学习任务记录失败')
  } finally {
    loading.value = false
  }
}

// 格式化时间值，保证两位数显示
const formatTimeValue = (value) => {
  return String(value || 0).padStart(2, '0')
}

// 计算统计数据
const statistics = computed(() => {
  const missionStats = new Map()
  
  // 定义一个颜色数组，用于为任务分配不同的颜色
  const colorPalette = [
    '#4573ff', // 蓝色
    '#5856d6', // 紫色
    '#bf5af2', // 紫红色
    '#34c759', // 绿色
    '#ff9f0a', // 橙色
    '#ff375f', // 红色
    '#30d158', // 浅绿色
    '#ff9500', // 深橙色
    '#64d2ff', // 浅蓝色
    '#5e5ce6', // 非活跃蓝色
    '#ac8e68', // 棕色
    '#ff6b6b', // 浅红色
    '#ffd60a', // 黄色
    '#00c8d6', // 青色
    '#a2845e'  // 土色
  ]
  
  // 为每个任务分配唯一的颜色
  const missionColorMap = {}
  
  let totalSeconds = 0
  
  // 第一次遍历：计算总秒数
  subjectList.value.forEach(mission => {
    if (mission.totalTime) {
      const [hours, minutes, seconds] = mission.totalTime.split(':').map(Number)
      totalSeconds += hours * 3600 + minutes * 60 + seconds
    }
  })

  // 首先为所有任务分配颜色
  // 先收集所有任务名称
  const allMissions = subjectList.value.map(mission => mission.mission)
  // 去除重复任务
  const uniqueMissions = [...new Set(allMissions)]
  
  // 为每个任务分配一个颜色
  uniqueMissions.forEach((missionName, index) => {
    // 使用颜色数组中的颜色，如果超出范围则生成新颜色
    if (index < colorPalette.length) {
      missionColorMap[missionName] = colorPalette[index]
    } else {
      missionColorMap[missionName] = generateColorFromString(missionName)
    }
  })
  
  // 第二次遍历：计算每个任务的统计信息
  subjectList.value.forEach(mission => {
    let subjectSeconds = 0
    
    if (mission.totalTime) {
      const [hours, minutes, seconds] = mission.totalTime.split(':').map(Number)
      subjectSeconds = hours * 3600 + minutes * 60 + seconds
    }
    
    const missionKey = mission.mission
    if (!missionStats.has(missionKey)) {
      missionStats.set(missionKey, {
        seconds: subjectSeconds,
        label: mission.mission,
        // 使用预分配的颜色
        color: missionColorMap[mission.mission],
        subject: mission.subject,
        totalTime: mission.totalTime || '00:00:00',
        percentage: totalSeconds > 0 ? (subjectSeconds / totalSeconds * 100) : 0
      })
    } else {
      const existingStats = missionStats.get(missionKey)
      existingStats.seconds += subjectSeconds
      
      // 更新累计时间显示
      const totalSecs = existingStats.seconds
      existingStats.totalTime = [
        Math.floor(totalSecs / 3600).toString().padStart(2, '0'),
        Math.floor((totalSecs % 3600) / 60).toString().padStart(2, '0'),
        (totalSecs % 60).toString().padStart(2, '0')
      ].join(':')
      
      // 更新百分比
      existingStats.percentage = totalSeconds > 0 ? (existingStats.seconds / totalSeconds * 100) : 0
    }
  })
  
  const statsArray = Array.from(missionStats.values()).map(stat => ({
    ...stat,
    hours: Math.floor(stat.seconds / 3600),
    minutes: Math.floor((stat.seconds % 3600) / 60),
    seconds: stat.seconds % 60
  }))

  return {
    subjects: statsArray.sort((a, b) => b.seconds - a.seconds), // 按时间降序排序
    hours: Math.floor(totalSeconds / 3600),
    minutes: Math.floor((totalSeconds % 3600) / 60),
    seconds: totalSeconds % 60,
    totalSeconds
  }
})

// 状态变量
const loading = ref(false)
const error = ref(null)
const trendData = ref(null)

// 获取学习时间趋势数据
const fetchTrendData = async () => {
  try {
    const response = await request.get('/api/study/trend')
    
    if (response.code === '200') {
      console.log('API返回趋势数据:', response.data)
      trendData.value = response.data
      // 更新折线图
      updateLineChart()
    } else {
      error.value = response.message || '获取学习时间趋势数据失败'
      ElMessage.error(error.value)
    }
  } catch (err) {
    console.error('获取学习时间趋势数据失败:', err)
    error.value = '网络错误，请稍后重试'
    ElMessage.error('获取学习时间趋势数据失败')
  }
}

// 处理趋势数据的函数
const processTrendData = (data) => {
  if (!data) return { dates: [], missions: [], series: [] }
  
  // 打印原始数据以便调试
  console.log('原始趋势数据:', JSON.stringify(data, null, 2))
  
  // 按日期排序的所有日期
  const dates = Object.keys(data).sort()
  
  // 收集所有任务名称
  const allMissions = new Set()
  dates.forEach(date => {
    data[date].forEach(item => {
      if (item.mission) {
        allMissions.add(item.mission)
      }
    })
  })
  const missions = Array.from(allMissions)
  
  // 为每个任务创建一个系列
  const series = missions.map((mission, index) => {
    // 为每个任务分配一个颜色
    const colors = [
      '#4573ff', // 蓝色
      '#ac8e68', // 棕色
      '#ff9f0a', // 橙色
      '#34c759', // 绿色
      '#5856d6', // 紫色
      '#ff2d55', // 红色
      '#007aff', // 深蓝色
      '#5ac8fa'  // 浅蓝色
    ]
    const colorIndex = index % colors.length
    
    // 收集每个日期的数据
    const seriesData = dates.map(date => {
      const dayData = data[date]
      const missionData = dayData.find(item => item.mission === mission)
      
      // 如果该日期有该任务的数据，返回总秒数，否则返回0
      return missionData ? missionData.totalSeconds : 0
    })
    
    // 创建一个包含原始数据的自定义数据对象
    const customData = dates.map(date => {
      const dayData = data[date]
      const missionData = dayData.find(item => item.mission === mission)
      return {
        date,
        mission,
        totalSeconds: missionData ? missionData.totalSeconds : 0,
        time: missionData ? missionData.time : '00:00:00',
        studyDate: missionData ? missionData.studyDate : date
      }
    })
    
    return {
      name: mission,
      type: 'line',
      smooth: true,
      symbolSize: 6,
      data: seriesData,
      // 存储自定义数据供tooltip使用
      customData: customData,
      itemStyle: {
        color: colors[colorIndex]
      },
      lineStyle: {
        width: 3
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: `rgba(${hexToRgb(colors[colorIndex])}, 0.3)`
          }, {
            offset: 1, color: `rgba(${hexToRgb(colors[colorIndex])}, 0.1)`
          }]
        }
      }
    }
  })
  
  // 打印处理后的数据
  console.log('处理后的趋势数据:', { dates, missions })
  console.log('系列数据示例:', series.length > 0 ? series[0].customData : [])
  
  return { dates, missions, series }
}

// 转换十六进制颜色为RGB格式
const hexToRgb = (hex) => {
  // 去除#前缀
  hex = hex.replace('#', '')
  
  // 将十六进制转换为RGB
  const r = parseInt(hex.substring(0, 2), 16)
  const g = parseInt(hex.substring(2, 4), 16)
  const b = parseInt(hex.substring(4, 6), 16)
  
  return `${r}, ${g}, ${b}`
}

// 更新图表
const updateChart = () => {
  console.log('开始更新图表')
  // 如果图表元素不存在或者没有数据，则不创建图表
  if (!pieChart.value) {
    console.log('图表元素不存在')
    return
  }
  
  console.log('图表元素存在，大小:', pieChart.value.clientWidth, 'x', pieChart.value.clientHeight)
  
  // 检查是否有数据
  const hasData = statistics.value.subjects && statistics.value.subjects.some(item => item.seconds > 0)
  if (!hasData) {
    console.log('没有有效的学习数据显示')
  }
  
  try {
    // 强制设置容器大小
    pieChart.value.style.width = '100%'
    pieChart.value.style.height = '450px'
    
    // 清除现有实例，避免重复初始化
    echarts.dispose(pieChart.value)
    
    // 初始化新图表
    const chart = echarts.init(pieChart.value)
    console.log('初始化图表成功，容器大小:', pieChart.value.clientWidth, 'x', pieChart.value.clientHeight)
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          const data = params.data
          const timeStr = data.totalTime || '00:00:00'
          const percent = data.percentage.toFixed(1)
          return `${data.name}<br/>学习时间：${timeStr} (${percent}%)`
        },
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#eee',
        borderWidth: 1,
        padding: [8, 12],
        textStyle: {
          color: '#1a1f36',
          fontSize: 14
        }
      },
      series: [
        {
          type: 'pie',
          radius: '85%',
          // 不使用玫瑰图模式，保持圆形图宽度一致
          roseType: false,
          // 移除最小角度限制，让占比准确反映
          minAngle: 0.1,
          // 数据排序，确保小数据不会相邻
          clockwise: true,
          startAngle: 90,
          endAngle: 450,
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          // 显示标签
          label: {
            show: true,
            position: 'outside',
            formatter: (params) => {
              // 只显示名称和时间
              return `${params.name}\n学习时间：${params.data.totalTime}`
            },
            color: '#1a1f36',
            fontSize: 12,
            lineHeight: 18,
            padding: [4, 8],
            backgroundColor: 'rgba(255, 255, 255, 0.7)',
            borderRadius: 4
          },
          // 标签连接线
          labelLine: {
            show: true,
            length: 10,
            length2: 10,
            smooth: true
          },
          emphasis: {
            scale: true,
            scaleSize: 4,
            itemStyle: {
              shadowBlur: 20,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.15)'
            }
          },
          // 过滤掉学习时间为0的任务，只显示有学习时间的任务
          data: statistics.value.subjects
            .filter(item => item.seconds > 0)
            .map(item => ({
              value: item.percentage,
              name: item.label,
              totalTime: item.totalTime,
              percentage: item.percentage,
              itemStyle: { color: item.color }
            }))
        }
      ]
    }
    console.log(statistics.value.subjects)
    chart.setOption(option)
    console.log('图表选项设置完成')
    
    // 监听窗口大小变化，自动调整图表大小
    window.addEventListener('resize', () => {
      if (chart && !chart.isDisposed()) {
        chart.resize()
      }
    })
  } catch (err) {
    console.error('图表创建失败:', err)
    error.value = '图表创建失败'
  }
}

// 更新折线图
const updateLineChart = () => {
  if (!lineChart.value) {
    console.log('折线图元素不存在')
    return
  }
  
  if (!trendData.value) {
    console.log('折线图数据不存在，尝试获取数据')
    fetchTrendData()
    return
  }
  
  try {
    // 设置容器大小
    lineChart.value.style.width = '100%'
    lineChart.value.style.height = '400px'
    
    // 清除现有实例
    echarts.dispose(lineChart.value)
    
    // 初始化新图表
    const chart = echarts.init(lineChart.value)
    
    // 处理趋势数据
    const processedData = processTrendData(trendData.value)
    
    const option = {
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#eee',
        borderWidth: 1,
        padding: [8, 12],
        textStyle: {
          color: '#1a1f36',
          fontSize: 14
        },
        formatter: function(params) {
          let result = params[0].axisValue + '<br/>';
          
          // 直接从trendData中获取数据
          const date = params[0].axisValue;
          
          if (trendData.value && trendData.value[date]) {
            // 打印原始数据以便调试
            console.log('该日期的原始数据:', date, trendData.value[date]);
            
            // 遍历所有参数（每个系列）
            params.forEach(param => {
              const mission = param.seriesName;
              let timeStr = '00:00:00';
              
              // 在该日期的数据中查找对应任务的记录
              const missionData = trendData.value[date].find(item => item.mission === mission);
              
              if (missionData) {
                console.log('找到任务数据:', mission, missionData);
                
                // 优先使用time属性
                if (missionData.time && missionData.time !== '00:00:00') {
                  timeStr = missionData.time;
                  console.log('使用time属性:', timeStr);
                } 
                // 如果没有time属性或为零，则使用totalSeconds计算
                else if (missionData.totalSeconds) {
                  const totalSeconds = missionData.totalSeconds;
                  const hours = Math.floor(totalSeconds / 3600);
                  const minutes = Math.floor((totalSeconds % 3600) / 60);
                  const seconds = totalSeconds % 60;
                  timeStr = 
                    (hours < 10 ? '0' + hours : hours) + ':' + 
                    (minutes < 10 ? '0' + minutes : minutes) + ':' + 
                    (seconds < 10 ? '0' + seconds : seconds);
                  console.log('使用totalSeconds计算时间:', totalSeconds, '->', timeStr);
                }
              } else {
                console.log('未找到任务数据:', mission);
              }
              
              result += `${param.marker} ${mission}: ${timeStr}<br/>`;
            });
          } else {
            // 如果没有找到该日期的数据，则使用默认的格式化方法
            params.forEach(param => {
              const totalSeconds = param.value;
              const hours = Math.floor(totalSeconds / 3600);
              const minutes = Math.floor((totalSeconds % 3600) / 60);
              const seconds = totalSeconds % 60;
              const timeStr = 
                (hours < 10 ? '0' + hours : hours) + ':' + 
                (minutes < 10 ? '0' + minutes : minutes) + ':' + 
                (seconds < 10 ? '0' + seconds : seconds);
              
              result += `${param.marker} ${param.seriesName}: ${timeStr}<br/>`;
            });
          }
          
          return result;
        }
      },
      legend: {
        data: processedData.missions,
        top: 5,
        right: 10,
        itemWidth: 15,
        itemHeight: 10,
        textStyle: {
          color: '#697386',
          fontSize: 12
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: processedData.dates,
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#666',
          fontSize: 12,
          formatter: function(value) {
            // 只显示月份和日期，例如 '05-12'
            return value.substring(5);
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '学习时间（小时）',
        nameTextStyle: {
          color: '#666',
          fontSize: 12,
          padding: [0, 0, 0, 5]
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#666',
          fontSize: 12,
          formatter: function(value) {
            // 将秒数转换为小时显示
            return (value / 3600).toFixed(1);
          }
        }
      },
      series: processedData.series.length > 0 ? processedData.series : [
        {
          name: '高数30讲',
          type: 'line',
          smooth: true,
          symbolSize: 6,
          data: [120, 132, 101, 134, 90, 230, 210],
          itemStyle: {
            color: '#4573ff' // 蓝色
          },
          lineStyle: {
            width: 3
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(69, 115, 255, 0.3)'
              }, {
                offset: 1, color: 'rgba(69, 115, 255, 0.1)'
              }]
            }
          }
        },
        {
          name: '880',
          type: 'line',
          smooth: true,
          symbolSize: 6,
          data: [220, 182, 191, 234, 290, 330, 310],
          itemStyle: {
            color: '#ac8e68' // 棕色
          },
          lineStyle: {
            width: 3
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(172, 142, 104, 0.3)'
              }, {
                offset: 1, color: 'rgba(172, 142, 104, 0.1)'
              }]
            }
          }
        },
        {
          name: 'Video Ads',
          type: 'line',
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(88, 86, 214, 0.3)'
              }, {
                offset: 1, color: 'rgba(88, 86, 214, 0.1)'
              }]
            }
          }
        }
      ]
    };
    
    chart.setOption(option)
    
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      if (chart && !chart.isDisposed()) {
        chart.resize()
      }
    })
  } catch (err) {
    console.error('折线图创建失败:', err)
  }
}

// 监听数据变化更新图表
// 添加immediate: false选项，避免在DOM渲染前触发
watch(() => statistics.value, (newVal, oldVal) => {
  // 确保只在有真实数据变化时才更新图表
  if (pieChart.value && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
    console.log('数据变化触发图表更新')
    updateChart()
    updateLineChart()
  }
}, { deep: true, immediate: false })

// 监听时间范围变化
watch(timeRange, () => {
  fetchSubjectList()
})

onMounted(() => {
  // 先获取数据
  fetchSubjectList()
  
  // 获取趋势数据
  fetchTrendData()
  
  // 使用更长的延迟并添加多次尝试机制
  let attempts = 0;
  const maxAttempts = 5;
  const checkAndInitChart = () => {
    attempts++;
    if (pieChart.value) {
      console.log(`在第${attempts}次尝试中成功初始化图表`)
      updateChart()
    } else if (attempts < maxAttempts) {
      console.log(`第${attempts}次尝试: pieChart元素仍然不存在，将再次尝试`)
      setTimeout(checkAndInitChart, 200 * attempts) // 每次尝试增加等待时间
    } else {
      console.error('在多次尝试后，pieChart元素仍然不存在')
    }
  }
  
  // 初始化图表的函数
  const initCharts = () => {
    let attempts = 0;
    const maxAttempts = 10;
    
    const checkAndInitCharts = () => {
      attempts++;
      const pieChartExists = pieChart.value !== null;
      const lineChartExists = lineChart.value !== null;
      
      if (pieChartExists && lineChartExists) {
        console.log(`在第${attempts}次尝试中成功初始化所有图表`);
        updateChart();
        updateLineChart();
        return;
      } else {
        if (pieChartExists) {
          updateChart();
        }
        if (lineChartExists) {
          updateLineChart();
        }
        
        if (attempts < maxAttempts) {
          console.log(`第${attempts}次尝试: 部分图表元素仍然不存在，将再次尝试`);
          setTimeout(checkAndInitCharts, 300 * attempts);
        } else {
          console.error('在多次尝试后，部分图表元素仍然不存在');
        }
      }
    };
    
    // 开始第一次尝试
    setTimeout(checkAndInitCharts, 200);
  };
  
  // 启动初始化
  initCharts();
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    if (pieChart.value) {
      try {
        const chart = echarts.getInstanceByDom(pieChart.value) || echarts.init(pieChart.value);
        chart.resize();
      } catch (err) {
        console.error('调整图表大小失败:', err);
      }
    }
    
    if (lineChart.value) {
      try {
        const chart = echarts.getInstanceByDom(lineChart.value) || echarts.init(lineChart.value);
        chart.resize();
      } catch (err) {
        console.error('调整折线图大小失败:', err);
      }
    }
  });
})
</script>

<style scoped>
.dashboard-container {
  padding: 12px;
  background-color: #f6f8fc;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
}

.chart-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  width: 100%;
}

/* 折线图样式 */

.trend-chart-container {
  padding: 20px;
}

.trend-chart {
  width: 100%;
  height: 300px;
}

.chart-wrapper {
  background: transparent;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.header-section {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-group {
  display: flex;
  flex-direction: column;
}

.title-group h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a1f36;
}

.date-countdown-info {
  margin-top: 4px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 15px;
}

.date-info {
  font-size: 13px;
  color: #697386;
}

.countdown-info {
  font-size: 13px;
  color: #e6a23c;
  background-color: rgba(230, 162, 60, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-flex;
  align-items: center;
}

.countdown-info strong {
  color: #e6a23c;
  font-size: 15px;
  font-weight: 600;
  margin: 0 2px;
}

:deep(.el-radio-group) {
  --el-color-primary: #4573ff;
}

:deep(.el-radio-button__inner) {
  border: 1px solid #e4e7ed;
  padding: 6px 16px;
  font-size: 13px;
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid #e4e7ed;
  border-radius: 6px 0 0 6px;
}

:deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 6px 6px 0;
}

.chart-section {
  padding: 20px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  align-items: start;
}

.chart-area {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  height: 500px; /* 增大图表区域高度 */
  width: 100%;
  min-height: 500px;
}

.center-stats {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  z-index: 1;
  background: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 50%;
  width: 220px;
  height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.time-display {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
}

.time-block {
  text-align: center;
}

.time-value {
  font-size: 32px;
  font-weight: 600;
  color: #1a1f36;
  line-height: 1;
  font-variant-numeric: tabular-nums;
}

.time-label {
  margin-top: 4px;
  font-size: 12px;
  color: #697386;
}

.time-separator {
  font-size: 32px;
  font-weight: 500;
  color: #1a1f36;
  margin-top: -4px;
}

.total-label {
  font-size: 14px;
  color: #697386;
}

.pie-chart {
  width: 100%;
  height: 100%;
  position: relative;
  min-height: 300px;
  min-width: 300px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 10px;
}

.stat-item {
  background: #f8fafc;
  border-radius: 10px;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.2s ease;
}

.stat-item:hover {
  background: #f1f5f9;
  transform: translateY(-2px);
}

.stat-item.active {
  background: #f1f5f9;
}

.stat-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stat-color {
  width: 8px;
  height: 8px;
  border-radius: 4px;
}

.stat-name {
  font-size: 14px;
  color: #1a1f36;
  font-weight: 500;
}

.stat-time {
  font-variant-numeric: tabular-nums;
  font-size: 14px;
  font-weight: 500;
  color: #4573ff;
}

.stat-separator {
  margin: 0 2px;
  color: #697386;
  font-weight: normal;
}

@media (max-width: 640px) {
  .dashboard-container {
    padding: 8px;
  }

  .chart-section {
    padding: 16px;
    grid-template-columns: 1fr;
  }

  .chart-area {
    height: 300px;
  }

  .center-stats {
    width: 180px;
    height: 180px;
    padding: 16px;
  }

  .time-value {
    font-size: 20px;
  }

  .time-separator {
    font-size: 20px;
  }
}
</style> 